<template>
    <div class="container">
        <!-- 导航栏 -->
        <AtjHeader></AtjHeader>
        <!-- 加载状态 -->
        <div v-show="!loading" class="loading-state">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
        </div>
        <!-- 错误状态 -->
        <div v-show="error" class="error-state">
            <p>{{ error }}</p>
            <button @click="fetchArticle">重试</button>
        </div>
        
        <div class="article-container">
            <!-- 文章头部 -->
            <div class="article-header">
                <h1 class="article-title">{{contants?.title}}</h1>
                <div class="article-meta">
                    <span class="article-date">
                        <i class="icon-calendar"></i>
                        {{formatDate(contants?.updated_at)}}
                    </span>
                    <span class="article-author">
                        <i class="icon-user"></i>
                        {{contants?.author_name}}
                    </span>
                    <span class="article-category">
                        <i class="icon-folder"></i>
                        {{contants?.category_name}}
                    </span>
                    <span class="article-views">
                        <i class="icon-eye"></i>
                        {{contants?.view_count}} 阅读
                    </span>
                </div>
                <div class="article-tags">
                    <span class="tag" v-for="item in contants?.tags" :key="item">{{item}}</span>
                </div>
            </div>

                

            <!-- 文章内容 -->
            <article class="article-content">
                <div v-html="contants?.content"></div>
            </article>
            <!-- 在文章内容旁边添加目录 -->
            <div class="article-toc" v-if="toc.length > 0">
                <h3 class="toc-title">目录</h3>
                <nav class="toc-nav">
                    <ul>
                        <li v-for="item in toc" 
                            :key="item.id" 
                            :class="[`level-${item.level}`, { active: currentHeading === item.id }]"
                        >
                            <a 
                                :href="`#${item.id}`" 
                                @click.prevent="scrollToHeading(item.id)"
                            >
                                {{ item.text }}
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
            <!-- 文章底部 -->
            <div class="article-footer">
                <div class="article-tags">
                    <span class="tag" v-for="item in contants?.tags" :key="item">{{item}}</span>
                </div>
                
                <div class="article-share">
                    <span>分享到：</span>
                    <a href="#" class="share-item">微信</a>
                    <a href="#" class="share-item">微博</a>
                    <a href="#" class="share-item">Twitter</a>
                </div>

                <div class="article-navigation">
                    <div class="prev-article" @click="goToArticle(prevArticle.id)" v-if="prevArticle">
                        <span>上一篇</span>
                        <a>{{ prevArticle.title }}</a>
                    </div>
                    <span v-else>没有上一篇文章</span>
                    <div class="next-article" @click="goToArticle(nextArticle.id)" v-if="nextArticle">
                        <span>下一篇</span>
                        <a>{{ nextArticle.title }}</a>
                    </div>
                    <span v-else>没有下一篇文章</span>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
                <h3>评论 ({{ comments.length }})</h3>
                
                <!-- 评论表单 -->
                <div class="comment-form">
                    <div class="comment-user-info" v-if="!isLoggedIn">
                        <input 
                            v-model="commentForm.nickname" 
                            type="text" 
                            placeholder="昵称（选填）"
                        >
                        <input 
                            v-model="commentForm.email" 
                            type="email" 
                            placeholder="邮箱（选填）"
                        >
                    </div>
                    <textarea 
                        v-model="commentForm.content" 
                        placeholder="写下你的评论..."
                        :class="{ 'replying': replyTo }"
                    ></textarea>
                    <div class="comment-form-footer">
                        <div class="reply-info" v-if="replyTo">
                            回复 @{{ replyTo.nickname }}
                            <button class="cancel-reply" @click="cancelReply">取消回复</button>
                        </div>
                        <button 
                            class="submit-comment" 
                            @click="submitComment"
                            :disabled="!commentForm.content.trim()"
                        >
                            发表评论
                        </button>
                    </div>
                </div>

                <!-- 评论列表 -->
                <div class="comments-list">
                    <div 
                        v-for="comment in comments" 
                        :key="comment.id" 
                        class="comment-item"
                        :class="{ 'has-replies': comment.replies?.length }"
                    >
                        <div class="comment-avatar">
                            <img :src="getAvatarUrl(comment.email)" alt="avatar">
                        </div>
                        <div class="comment-content">
                            <div class="comment-header">
                                <span class="comment-author">{{ comment.nickname || '匿名用户' }}</span>
                                <span class="comment-date">{{ formatDate(comment.created_at) }}</span>
                            </div>
                            <div class="comment-text">{{ comment.content }}</div>
                            <div class="comment-actions">
                                <button class="reply-btn" @click="replyToComment(comment)">回复</button>
                                <button 
                                    class="delete-btn" 
                                    v-if="canDelete(comment)"
                                    @click="deleteComment(comment.id)"
                                >
                                    删除
                                </button>
                            </div>
                            
                            <!-- 嵌套回复 -->
                            <div class="comment-replies" v-if="comment.replies?.length">
                                <div 
                                    v-for="reply in comment.replies" 
                                    :key="reply.id"
                                    class="reply-item"
                                >
                                    <div class="comment-avatar">
                                        <img :src="getAvatarUrl()" alt="avatar">
                                    </div>
                                    <div class="comment-content">
                                        <div class="comment-header">
                                            <span class="comment-author">{{ reply.nickname || '匿名用户' }}</span>
                                            <span class="comment-date">{{ formatDate(reply.created_at) }}</span>
                                        </div>
                                        <div class="comment-text">
                                            <span class="reply-to">@{{ reply.reply_to_nickname }}</span>
                                            {{ reply.content }}
                                        </div>
                                        <div class="comment-actions">
                                            <button class="reply-btn" @click="replyToComment(reply, comment)">回复</button>
                                            <button 
                                                class="delete-btn" 
                                                v-if="canDelete(reply)"
                                                @click="deleteComment(reply.id)"
                                            >
                                                删除
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 相关文章推荐 -->
            <div class="related-articles">
                <h3>相关文章</h3>
                <div class="related-articles-list">
                    <div v-for="article in relatedArticles" 
                        :key="article.title" 
                        @click="goToArticle(article.id)"
                        class="related-article-item">
                    <a class="related-article-link">
                        <div class="related-article-thumbnail">
                        <img :src="article.thumbnail_url" :alt="article.title">
                        </div>
                        <div class="related-article-info">
                        <h4>{{ article.title }}</h4>
                        <p>{{ article.description }}</p>
                        <span class="related-article-date">{{ formatDate(article.created_at) }}</span>
                        </div>
                    </a>
                    </div>
                </div>
            </div>
        </div>
        <footer class="footer">
            <p>&copy; 2024 我的博客. All rights reserved.</p>
        </footer>
    </div>

    <!-- 返回顶部按钮 -->
    <button 
        class="back-to-top" 
        :class="{ visible: isBackToTopVisible }"
        @click="scrollToTop"
        title="返回顶部"
    >
        ↑
    </button>
</template>
<script setup lang="ts">
import { ref, onMounted, defineComponent, watch, nextTick, onUnmounted } from 'vue';
import { articleApi } from '@/api/article'
import { tagApi } from '@/api/tag'
import { commentApi } from '@/api/comment'
import { formatDate } from '@/utils/date'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css'; // 可以选择其他主题样式     // GitHub风格（浅色）
import AtjHeader from '@/components/AtjHeader.vue'
defineComponent({
  name: 'ArticleView',
});
// 在 setup 中
const router = useRouter()
const route = useRoute()
// 获取路由参数
const id = route.params.id  // /article/:id
const hash = route.hash  // #section1

// 状态
const loading = ref(false)
const error = ref('')
const contants = ref()
interface Article {
    id: number;
    title: string;
}

const articles = ref<Article[]>([])
const currentArticle = ref<Article | null>(null)
const prevArticle = ref<Article | null>(null)
const nextArticle = ref<Article | null>(null)
// 相关文章数据
const relatedArticles = ref([
]);
// 使用防抖来避免频繁切换加载状态
const setLoading = (value: boolean) => {
    if (value) {
        loading.value = true
    } else {
        // 延迟关闭loading状态，避免闪烁
        setTimeout(() => {
            loading.value = false
        }, 300)
    }
}

const goToArticle = async (id?: number) => {
    if (!id) return
    try {
        setLoading(true)
        await router.push({ 
            path: '/article', 
            query: { id: id.toString() } 
        })
        // 重新获取文章数据
        await fetchArticle()
        await fetchArticles()
        // 重新获取评论列表
        await fetchComments()
    } catch (err) {
        console.error('Navigation failed:', err)
        error.value = '页面跳转失败，请重试'
    }
}
// 自定义 debounce 函数
const debounce = <T extends (...args: any[]) => any>(
    fn: T,
    delay: number
) => {
    let timeoutId: ReturnType<typeof setTimeout>
    
    return function (this: any, ...args: Parameters<T>) {
        clearTimeout(timeoutId)
        timeoutId = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}
// 使用防抖处理路由变化
const debouncedFetchArticle = debounce(async () => {
    await fetchArticle()
}, 300)

// 监听路由变化
watch(
    () => route.query.id,
    async (newId, oldId) => {
        if (newId && newId !== oldId) {
            await debouncedFetchArticle()
        }
    }
)
const fetchArticle = async () =>{
    try {
        setLoading(true)
        error.value = ''
        
        const articleId = route.query.id
        if (!articleId) {
            error.value = '文章ID不存在'
            return
        }

        const response = await articleApi.getArticleById(articleId as string)
        if (response) {
            if (response) {
                // 清理 pre 标签的 style 属性
                if (response.content) {
                    response.content = response.content.replace(/<pre style="[^"]*">/g, '<pre>')
                }
                contants.value = response
            } else {
                error.value = '文章不存在'
            }
            // 增加浏览量
            await articleApi.addView(articleId as string)
            // 获取标签下的所有文章
            const Tags = await tagApi.getTags()
            const Tags_id = []
            response.tags.forEach(element => {
                for(let i = 0; i < Tags.length; i++){
                    if(Tags[i].name === element){
                        Tags_id.push(Tags[i].id)
                    }
                }
            });
            // 存储所有文章的临时数组
            let allArticles: Article[] = []
            
            // 获取每个标签的文章并合并
            for(let i = 0; i < Tags_id.length; i++){
                const tagArticles = await tagApi.getArticlesByTag(Tags_id[i])
                if (Array.isArray(tagArticles)) {
                    // 将新文章添加到数组中，避免重复
                    tagArticles.forEach(article => {
                        if (!allArticles.some(existingArticle => existingArticle.id === article.id)) {
                            allArticles.push(article)
                        }
                    })
                }
            }
            
            // 按id降序排序（最新的文章在前）
            allArticles.sort((a, b) => b.id - a.id)
            
            // 更新到响应式引用 相关文件
            relatedArticles.value = allArticles
            // 获取所有文章并设置上下篇
            await fetchArticles()
            loading.value = true
        } else {
            error.value = '文章不存在'
        }
    } catch (err) {
        error.value = '获取文章失败，请稍后重试'
        console.error('Error fetching article:', err)
    }
}
// 获取所有文章并设置上下篇
const fetchArticles = async () => {
    try {
        // 获取所有文章
        const response = await articleApi.getArticles({})
        if (response && response.data) {
            // 按id降序排序（最新的文章在前）
            const sortedArticles = response.data.sort((a, b) => b.id - a.id)
            articles.value = sortedArticles

            // 获取当前文章的索引
            const currentId = Number(route.query.id)
            const currentIndex = sortedArticles.findIndex(article => article.id === currentId)

            if (currentIndex !== -1) {
                currentArticle.value = sortedArticles[currentIndex]
                // 设置上一篇文章（如果存在）
                prevArticle.value = currentIndex > 0 ? sortedArticles[currentIndex - 1] : null
                // 设置下一篇文章（如果存在）
                nextArticle.value = currentIndex < sortedArticles.length - 1 ? sortedArticles[currentIndex + 1] : null
            }
        }
    } catch (err) {
        console.error('Error fetching articles:', err)
    }
}
// 等待文章数据加载完成
const waitForArticle = () => {
    return new Promise((resolve, reject) => {
        // 如果已经有数据，直接返回
        if (contants.value) {
            resolve(contants.value)
            return
        }

        // 设置超时
        const timeout = setTimeout(() => {
            reject(new Error('加载文章超时'))
        }, 10000) // 10秒超时

        // 监听数据变化
        const unwatch = watch(contants, (newValue) => {
            if (newValue) {
                clearTimeout(timeout)
                unwatch() // 清除监听
                resolve(newValue)
            }
        })
    })
}
// 返回顶部按钮状态
const isBackToTopVisible = ref(false);

// 返回顶部方法
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

// 初始化代码高亮
const initializeCodeHighlight = () => {
    nextTick(() => {
        document.querySelectorAll('pre code').forEach((block) => {
            const pre = block.parentElement;
            if (!pre) return;

            // 检查是否已经高亮
            if (!block.classList.contains('hljs')) {
                // 现有的高亮逻辑
                const language = pre?.className.match(/language-(\w+)/)?.[1];
                if (language) {
                    block.classList.add(`language-${language}`);
                }
                
                // 添加复制按钮
                if (!pre.querySelector('.code-copy-btn')) {
                    const copyBtn = document.createElement('button');
                    copyBtn.className = 'code-copy-btn';
                    copyBtn.textContent = '复制';
                    copyBtn.addEventListener('click', () => copyCode(block as HTMLElement));
                    pre.appendChild(copyBtn);
                }

                // 添加展开按钮（如果代码块高度超过最大高度）
                if (block.offsetHeight > 350 && !pre.querySelector('.code-expand-btn')) {
                    const expandBtn = document.createElement('div');
                    expandBtn.className = 'code-expand-btn';
                    expandBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        pre.classList.toggle('expanded');
                        expandBtn.classList.toggle('expanded');
                    });
                    pre.appendChild(expandBtn);
                }
                
                hljs.highlightElement(block);
            }
        });
    });
}
// 复制代码功能
const copyCode = async (block: HTMLElement) => {
    try {
        const code = block.textContent || '';
        
        // 尝试使用新的 Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(code);
        } else {
            // 回退方法：创建临时文本区域
            const textArea = document.createElement('textarea');
            textArea.value = code;
            
            // 将文本区域移出可视区域
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            
            // 选择文本并复制
            textArea.select();
            document.execCommand('copy');
            
            // 清理
            textArea.remove();
        }
        
        // 获取复制按钮
        const copyBtn = block.parentElement?.querySelector('.code-copy-btn');
        if (copyBtn) {
            // 更改按钮文本显示复制成功
            const originalText = copyBtn.textContent;
            copyBtn.textContent = '已复制!';
            copyBtn.classList.add('copied');
            
            // 2秒后恢复原始文本
            setTimeout(() => {
                copyBtn.textContent = originalText;
                copyBtn.classList.remove('copied');
            }, 2000);
        }
    } catch (err) {
        console.error('Failed to copy code:', err);
        
        // 尝试使用备用方法
        try {
            const textArea = document.createElement('textarea');
            textArea.value = block.textContent || '';
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            textArea.remove();
            
            // 显示成功提示
            const copyBtn = block.parentElement?.querySelector('.code-copy-btn');
            if (copyBtn) {
                copyBtn.textContent = '已复制!';
                copyBtn.classList.add('copied');
                setTimeout(() => {
                    copyBtn.textContent = '复制';
                    copyBtn.classList.remove('copied');
                }, 2000);
            }
        } catch (fallbackErr) {
            console.error('Fallback copy failed:', fallbackErr);
            alert('复制失败，请手动复制');
        }
    }
}
// 监听内容变化，重新应用代码高亮
watch(() => contants.value?.content, (newContent) => {
    if (newContent) {
        console.log('Content changed, reinitializing code highlighting');
        initializeCodeHighlight();
    }
});
interface TocItem {
    id: string;
    text: string;
    level: number;
    element: HTMLElement;
}

const toc = ref<TocItem[]>([]);
const currentHeading = ref<string>('');

// 生成目录
const generateToc = () => {
    const article = document.querySelector('.article-content');
    if (!article) return;

    // 查找所有标题元素
    const headings = article.querySelectorAll('h1, h2, h3, h4, h5, h6');
    const tocItems: TocItem[] = [];

    headings.forEach((heading: HTMLElement) => {
        // 为每个标题生成唯一ID
        if (!heading.id) {
            heading.id = `heading-${tocItems.length + 1}`;
        }

        // 获取标题级别
        const level = parseInt(heading.tagName[1]);

        tocItems.push({
            id: heading.id,
            text: heading.textContent || '',
            level: level,
            element: heading
        });
    });

    toc.value = tocItems;
};

// 滚动到指定标题
const scrollToHeading = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
        // 获取header的高度（如果有固定header的话）
        const headerHeight = document.querySelector('.header')?.offsetHeight || 0;
        
        // 计算目标位置，考虑header的高度
        const targetPosition = element.offsetTop - headerHeight - 20; // 20px的额外偏移量
        
        // 平滑滚动
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
        
        // 更新当前标题
        currentHeading.value = id;
    }
};

// 更新当前可见的标题
const updateCurrentHeading = () => {
    const scrollPosition = window.scrollY;
    
    // 添加一些偏移量以提前高亮
    const offset = 100;

    // 找到当前可见的标题
    for (let i = toc.value.length - 1; i >= 0; i--) {
        const heading = toc.value[i];
        const element = heading.element;
        
        if (element.offsetTop - offset <= scrollPosition) {
            currentHeading.value = heading.id;
            return;
        }
    }

    // 如果没有找到，设置为第一个标题
    if (toc.value.length > 0) {
        currentHeading.value = toc.value[0].id;
    }
};

// 监听内容变化，重新生成目录
watch(() => contants.value?.content, () => {
    nextTick(() => {
        generateToc();
    });
});

// 监听滚动事件
let scrollHandler: number;
// 监听滚动
const handleScroll = () => {
    if (scrollHandler) {
        window.cancelAnimationFrame(scrollHandler);
    }
    scrollHandler = window.requestAnimationFrame(() => {
        updateCurrentHeading();
    });
};
// 评论相关的状态
const comments = ref([])
const commentForm = ref({
    content: '',
    nickname: '',
    email: ''
})
const replyTo = ref(null)
const isLoggedIn = ref(false) // 根据你的登录状态修改

// 获取评论列表
const fetchComments = async () => {
    try {
        const response = await commentApi.getComments(route.query.id as string)
        comments.value = response
    } catch (err) {
        console.error('获取评论失败:', err)
    }
}

// 提交评论
const submitComment = async () => {
    if (!commentForm.value.content.trim()) return
    
    try {
        
        const commentData = {
            article_id: route.query.id, // 确保这里使用正确的文章ID
            content: commentForm.value.content,
            parent_id: replyTo.value?.id || null,
            nickname: commentForm.value.nickname || '匿名用户',
            email: commentForm.value.email || null
        }
        console.log(commentData)
        await commentApi.addComment(commentData)
        // 重新获取评论列表
        await fetchComments()
        // 清空表单
        commentForm.value.content = ''
        commentForm.value.nickname = ''
        commentForm.value.email = ''
        replyTo.value = null
        
    } catch (err) {
        console.error('提交评论失败:', err)
        // 添加错误提示
    }
}

// 回复评论
const replyToComment = (comment, parentComment = null) => {
    replyTo.value = {
        id: comment.id,
        nickname: comment.nickname || '匿名用户'
    }
    // 滚动到评论框
    document.querySelector('.comment-form')?.scrollIntoView({ behavior: 'smooth' })
}

// 取消回复
const cancelReply = () => {
    replyTo.value = null
}

// 删除评论
const deleteComment = async (commentId) => {
    if (!confirm('确定要删除这条评论吗？')) return
    
    try {
        await commentApi.deleteComment(commentId)
        await fetchComments()
    } catch (err) {
        console.error('删除评论失败:', err)
    }
}

// 检查是否可以删除评论
const canDelete = (comment) => {
    // 根据你的业务逻辑修改，比如检查是否是评论作者或管理员
    return isLoggedIn.value
}

// 获取头像URL（使用Gravatar服务）
const getAvatarUrl = () => {
    // return `https://www.gravatar.com/avatar/${hash}?d=mp&s=50`
    return 'http://i1.hdslb.com/bfs/archive/6510bd5442b5428a28a674d6bb075c9b9e655009.jpg'
}

onMounted(async() => {
    generateToc();
    fetchComments()
    window.addEventListener('scroll', handleScroll);
    updateCurrentHeading();
    try {
        await fetchArticle()
        await waitForArticle()
        
        // 初始化代码高亮
        console.log('Article loaded, initializing code highlighting');
        initializeCodeHighlight();
        
    } catch (err) {
        error.value = err.message || '加载文章失败'
        console.error('Error:', err)
    }
});
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});
</script>
<style lang="less">
/* 确保在深色模式下保持样式 */
@media (prefers-color-scheme: dark) {
    pre {
        background-color: #1e1e1e !important;
    }
}
blockquote {
    margin: 1em 0;
    padding: 1em 2em;
    border-left: 4px solid var(--primary-color);
    background-color: #f8f9fa;
    color: #666;
    font-style: italic;

    &:before {
        content: '"';
        font-size: 2em;
        color: var(--primary-color);
        line-height: 0.1em;
        margin-right: 0.25em;
        vertical-align: -0.4em;
    }
    
    p {
        display: inline;
        margin: 0;
    }
}

img {
    max-width: 100%;
    height: auto;
}

a {
    color: var(--primary-color);
    text-decoration: none;

    &:hover {
        text-decoration: underline;
    }
}
p {
    margin: 0 0 1em;  // 添加段落间距
}

ul, ol {
    margin: 0 0 1em;
    padding-left: 2em;
}
.video-container {
    margin: 1em 0;
    max-width: 100%;
    
    .video-wrapper {
        position: relative;
        padding-bottom: 56.25%; /* 16:9 比例 */
        height: 0;
        overflow: hidden;
        
        iframe, video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 4px;
            background: #000;
        }
    }
}

</style>
<style lang="less" scoped>
@import '@/assets/css/universal.css';
/* 文章容器样式 */
.article-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 文章头部样式 */
.article-header {
    margin-bottom: 40px;
    text-align: center;
}

.article-title {
    font-size: 2.5em;
    color: #2c3e50;
    margin-bottom: 20px;
    line-height: 1.3;
}

.article-meta {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    color: #666;
    font-size: 14px;
    margin-bottom: 20px;
}

.article-meta span {
    display: flex;
    align-items: center;
    gap: 5px;
}

.article-tags {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
}

.tag {
    padding: 5px 15px;
    background-color: #f0f7ff;
    color: #1a73e8;
    border-radius: 20px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.tag:hover {
    background-color: #1a73e8;
    color: #fff;
    transform: translateY(-2px);
}

/* 文章目录样式 */
.article-toc {
    position: fixed;
    top: 245px;
    right: 20px;
    max-height: calc(100vh - 40px);
    overflow-y: auto;
    width: 250px;
    padding: 20px;
    margin-left: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .toc-title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 1px solid #eee;
        color: #333;
    }

    .toc-nav {
        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        li {
            margin: 4px 0;
            line-height: 1.4;

            a {
                display: block;
                padding: 4px 8px;
                color: #666;
                text-decoration: none;
                font-size: 14px;
                border-radius: 4px;
                transition: all 0.2s;

                &:hover {
                    color: var(--primary-color);
                    background: #f5f5f5;
                }
            }

            &.active > a {
                color: var(--primary-color);
                background: #f0f7ff;
                font-weight: 500;
            }
        }

        // 不同级别标题的缩进
        .level-1 { margin-left: 0; }
        .level-2 { margin-left: 12px; }
        .level-3 { margin-left: 24px; }
        .level-4 { margin-left: 36px; }
        .level-5 { margin-left: 48px; }
        .level-6 { margin-left: 60px; }
    }

    // 自定义滚动条
    &::-webkit-scrollbar {
        width: 4px;
    }

    &::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 2px;

        &:hover {
            background: #ccc;
        }
    }
}

// 响应式设计
@media (max-width: 1200px) {
    .article-toc {
        display: none;
    }
}

.toc-title {
    font-size: 16px;
    font-weight: 600;
    color: #1a73e8;
    margin-bottom: 15px;
}


/* 文章内容样式 */
.article-content {
    font-size: 16px;
    line-height: 1.8;
    color: #2c3e50;
}

.article-content section {
    margin-bottom: 40px;
}

.article-content h2 {
    font-size: 1.8em;
    color: #1a73e8;
    margin: 30px 0 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #eef2f7;
}

.article-content p {
    margin-bottom: 20px;
}

/* 代码块样式 */
.code-block {
    margin: 20px 0;
    border-radius: 10px;
    overflow: hidden;
}

.code-block pre {
    margin: 0;
    padding: 20px;
    background-color: #282c34;
    overflow-x: auto;
}

.code-block code {
    font-family: 'Fira Code', monospace;
    font-size: 14px;
    line-height: 1.6;
}

/* 文章底部样式 */
.article-footer {
    margin-top: 50px;
    padding-top: 30px;
    border-top: 1px solid #eef2f7;
}

.article-share {
    margin: 30px 0;
    display: flex;
    align-items: center;
    gap: 15px;
}

.share-item {
    padding: 8px 20px;
    border-radius: 20px;
    background-color: #f0f7ff;
    color: #1a73e8;
    text-decoration: none;
    transition: all 0.3s ease;
}

.share-item:hover {
    background-color: #1a73e8;
    color: #fff;
    transform: translateY(-2px);
}

.article-navigation {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
}

.prev-article,
.next-article {
    flex: 1;
    max-width: 45%;
    cursor: pointer;
}

.prev-article span,
.next-article span {
    display: block;
    color: #666;
    font-size: 14px;
    margin-bottom: 5px;
}

.prev-article a,
.next-article a {
    color: #1a73e8;
    text-decoration: none;
    font-weight: 500;
    transition: color 0.3s ease;
}

.prev-article a:hover,
.next-article a:hover {
    color: #0d47a1;
}

.next-article {
    text-align: right;
}

/* 评论区样式 */
.comments-section {
    margin-top: 50px;
    padding-top: 30px;
    border-top: 1px solid #eef2f7;
}

.comment-form {
    margin-bottom: 30px;
}

.comment-form textarea {
    width: 100%;
    height: 120px;
    padding: 15px;
    border: 1px solid #eef2f7;
    border-radius: 10px;
    resize: vertical;
    margin-bottom: 15px;
}

/* 返回顶部按钮 */
.back-to-top {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 40px;
    height: 40px;
    background-color: #1a73e8;
    color: #fff;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    opacity: 0;
    transition: all 0.3s ease;
    box-shadow: 0 2px 10px rgba(26, 115, 232, 0.3);
}

.back-to-top.visible {
    opacity: 1;
}

.back-to-top:hover {
    background-color: #0d47a1;
    transform: translateY(-3px);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .article-container {
        padding: 15px;
    }

    .article-title {
        font-size: 2em;
    }

    .article-toc {
        display: none;
    }

    .article-meta {
        flex-wrap: wrap;
    }

    .article-navigation {
        flex-direction: column;
        gap: 20px;
    }

    .prev-article,
    .next-article {
        max-width: 100%;
        text-align: left;
    }
}

/* 相关文章样式 */
.related-articles {
    margin-top: 50px;
    padding: 30px;
    background-color: #fff;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.related-articles h3 {
    color: #1a73e8;
    margin-bottom: 25px;
    font-size: 1.4em;
    position: relative;
    padding-left: 15px;
}

.related-articles h3::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 20px;
    background: linear-gradient(to bottom, #1a73e8, #8b5cf6);
    border-radius: 2px;
}

.related-articles-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 25px;
}

.related-article-item {
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
}

.related-article-link {
    text-decoration: none;
    color: inherit;
    display: block;
}

.related-article-thumbnail {
    width: 100%;
    height: 180px;
    overflow: hidden;
}

.related-article-thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.related-article-info {
    padding: 20px;
    background-color: #f8f9fa;
}

.related-article-info h4 {
    color: #2c3e50;
    font-size: 1.1em;
    margin-bottom: 10px;
    transition: color 0.3s ease;
}

.related-article-info p {
    color: #666;
    font-size: 14px;
    margin-bottom: 15px;
    line-height: 1.6;
}

.related-article-date {
    color: #888;
    font-size: 12px;
}

/* 悬浮效果 */
.related-article-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.related-article-item:hover .related-article-thumbnail img {
    transform: scale(1.05);
}

.related-article-item:hover .related-article-info h4 {
    color: #1a73e8;
}

/* 返回顶部按钮样式修复 */
.back-to-top {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 40px;
    height: 40px;
    background-color: #1a73e8;
    color: #fff;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    opacity: 0;
    visibility: hidden; /* 添加这行 */
    transition: all 0.3s ease;
    box-shadow: 0 2px 10px rgba(26, 115, 232, 0.3);
    font-size: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000; /* 确保按钮在最上层 */
}

.back-to-top.visible {
    opacity: 1;
    visibility: visible; /* 添加这行 */
}

/* 响应式适配 */
@media (max-width: 768px) {
    .related-articles {
        padding: 20px;
    }

    .related-articles-list {
        grid-template-columns: 1fr;
    }

    .related-article-thumbnail {
        height: 200px;
    }
}
.loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 200px;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #1a73e8;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}
/* 添加过渡效果 */
.loading-state,
.article-container,
.error-state {
    transition: opacity 0.3s ease;
}

.loading-state {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000;
}
.error-state {
    text-align: center;
    padding: 40px;
    color: #ff4d4f;

    button {
        margin-top: 20px;
        padding: 8px 16px;
        border: none;
        background-color: #1a73e8;
        color: white;
        border-radius: 4px;
        cursor: pointer;

        &:hover {
            background-color: #1557b0;
        }
    }
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
.comments-section {
    margin-top: 50px;
    padding-top: 30px;
    border-top: 1px solid #eef2f7;

    h3 {
        font-size: 1.5em;
        margin-bottom: 20px;
        color: #2c3e50;
    }
}

.comment-form {
    margin-bottom: 30px;
    
    .comment-user-info {
        display: flex;
        gap: 15px;
        margin-bottom: 15px;
        
        input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #eef2f7;
            border-radius: 4px;
            
            &:focus {
                border-color: var(--primary-color);
                outline: none;
            }
        }
    }

    textarea {
        width: 100%;
        height: 120px;
        padding: 15px;
        border: 1px solid #eef2f7;
        border-radius: 8px;
        resize: vertical;
        margin-bottom: 10px;
        
        &:focus {
            border-color: var(--primary-color);
            outline: none;
        }
        
        &.replying {
            border-color: var(--primary-color);
            background: #f8f9fa;
        }
    }
}

.comment-form-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .reply-info {
        color: #666;
        font-size: 14px;
        
        .cancel-reply {
            margin-left: 10px;
            color: #999;
            text-decoration: underline;
            cursor: pointer;
            
            &:hover {
                color: var(--primary-color);
            }
        }
    }
}

.submit-comment {
    padding: 8px 20px;
    background-color: var(--primary-color);
    color: #fff;
    border: none;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
        // 替换 darken 函数
        opacity: 0.9;
        transform: translateY(-2px);
    }
    
    &:disabled {
        background-color: #ccc;
        cursor: not-allowed;
        transform: none;
    }
}

.comments-list {
    .comment-item {
        display: flex;
        gap: 15px;
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #eef2f7;
        
        &:last-child {
            border-bottom: none;
        }
    }
    
    .comment-avatar {
        img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
    }
    
    .comment-content {
        flex: 1;
    }
    
    .comment-header {
        margin-bottom: 8px;
        
        .comment-author {
            font-weight: 500;
            color: #2c3e50;
        }
        
        .comment-date {
            margin-left: 10px;
            font-size: 12px;
            color: #999;
        }
    }
    
    .comment-text {
        color: #4a5568;
        line-height: 1.6;
        margin-bottom: 8px;
        
        .reply-to {
            color: var(--primary-color);
            margin-right: 5px;
        }
    }
    
    .comment-actions {
        button {
            padding: 4px 8px;
            font-size: 12px;
            color: #666;
            background: none;
            border: none;
            cursor: pointer;
            
            &:hover {
                color: var(--primary-color);
            }
        }
        
        .delete-btn {
            color: #ff4d4f;
            
            &:hover {
                color: darken(#ff4d4f, 10%);
            }
        }
    }
}

.comment-replies {
    margin-left: 55px;
    margin-top: 15px;
    
    .reply-item {
        display: flex;
        gap: 15px;
        margin-bottom: 15px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eef2f7;
        
        &:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
    }
}

// 深色模式支持
[data-theme="dark"] {
    .comments-section {
        border-top-color: rgba(255, 255, 255, 0.1);
    }
    
    .comment-form {
        textarea, input {
            background: #2d2d2d;
            border-color: #3d3d3d;
            color: #fff;
            
            &::placeholder {
                color: #666;
            }
        }
    }
    
    .comment-item {
        border-bottom-color: rgba(255, 255, 255, 0.1);
    }
    
    .comment-text {
        color: #ccc;
    }
    
    .comment-header .comment-author {
        color: #fff;
    }
}
</style>